package net.ufrog.common.weixin;

import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import net.ufrog.common.Logger;
import net.ufrog.common.utils.Cryptos;
import net.ufrog.common.utils.Cryptos.HashType;
import net.ufrog.common.weixin.pojos.JsTicket;

/**
 * 脚本接口
 * 
 * @author ultrafrog
 * @version 1.0, 2015-12-02
 * @since 1.0
 */
public abstract class JsApis {

	/**
	 * 读取脚本凭证
	 * 
	 * @param accessToken
	 * @return
	 */
	public static JsTicket getJsTicket(String accessToken) {
		String url = Apis.url(Apis.CGI_URL, "/ticket/getticket?access_token=%s&type=jsapi", accessToken);
		HttpResponse resp = HttpRequest.get(url).send();
		JsTicket jsTicket = Apis.fromJson(resp, JsTicket.class);
		return Apis.checkErr(jsTicket);
	}
	
	/**
	 * 脚本签名
	 * 
	 * @param noncestr
	 * @param jsTicket
	 * @param timestamp
	 * @param url
	 * @return
	 */
	public static String signJs(String noncestr, String jsTicket, Long timestamp, String url) {
		StringBuilder sign = new StringBuilder();
		sign.append("jsapi_ticket=").append(jsTicket);
		sign.append("&noncestr=").append(noncestr);
		sign.append("&timestamp=").append(timestamp);
		sign.append("&url=").append(url);
		Logger.debug("weixin jsapi sign: %s", sign);
		return Cryptos.hashAndHex(sign.toString(), HashType.SHA1);
	}
}
